package cn.codecrab.ai.langchain4j.store;

import cn.codecrab.ai.langchain4j.mongo.entity.ChatMessages;
import cn.codecrab.ai.langchain4j.mongo.service.ChatMessagesService;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

/**
 * @author 王刚
 * @since 2025年05月10日 15:42
 */
@Component
public class MongoChatMemoryStore implements ChatMemoryStore {

    @Resource
    private ChatMessagesService chatMessagesService;

    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        ChatMessages one = chatMessagesService.lambdaQuery().eq(ChatMessages::getMemoryId, memoryId).one();
        if (one == null) {
            return Collections.emptyList();
        }
        return ChatMessageDeserializer.messagesFromJson(one.getContent());
    }

    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> messages) {
        ChatMessages chatMessages = new ChatMessages();
        chatMessages.setMemoryId(memoryId.toString());
        chatMessages.setContent(ChatMessageSerializer.messagesToJson(messages));
        chatMessagesService.saveOrUpdateWrapper(chatMessages, chatMessagesService.lambdaQuery().eq(ChatMessages::getMemoryId, memoryId));
    }

    @Override
    public void deleteMessages(Object memoryId) {
        chatMessagesService.lambdaUpdate().eq(ChatMessages::getMemoryId, memoryId).remove();
    }

}
